package com.example.myapplication16_1;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * 服务器端程序
 *
 */
public class MyServer {
    private static final int PORT = 8888; // 服务器监听端口

    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        try {
            // 创建服务器Socket
            serverSocket = new ServerSocket(PORT);
            System.out.println("服务器已启动，等待客户端连接...");

            while (true) {
                // 等待客户端连接
                Socket client = serverSocket.accept();
                System.out.println("客户端已连接: " + client.getInetAddress().getHostAddress());

                // 获取当前时间
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
                String currentTime = sdf.format(new Date());
                String message = "服务器收到连接请求！当前时间: " + currentTime;

                // 发送消息给客户端
                OutputStream outputStream = client.getOutputStream();
                PrintStream printStream = new PrintStream(outputStream);
                printStream.println(message);
                System.out.println("已发送消息: " + message);

                printStream.close();
                client.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (serverSocket != null) {
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
} 